package cn.crc.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class EasyUDPClient {
    public static void main(String[] args)throws IOException {
        String messg = "我是小李，我想点一个芝士汉堡";//要发送的信息
        DatagramSocket socket = new DatagramSocket();//建立socket
        byte[] sendData;//建立收发容器
        byte[] receiveData = new byte[1024];

        sendData = messg.getBytes();//发送数据包
        InetAddress serverAddress = InetAddress.getByName("localhost");
        DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverAddress, 9999);
        socket.send(sendPacket);

        DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);//接收数据包
        socket.receive(receivePacket);
        String receivedMessage = new String(receivePacket.getData(),0, receivePacket.getLength());
        System.out.println("Received from server:"+ receivedMessage);

        socket.close();//关闭套接字
    }
}
